package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.dongdong.service.FreemarkerService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "dongdongshop_manager_web",consumerGroup = "dongdongshop_manager_web")
public class MQController implements RocketMQListener,RocketMQPushConsumerLifecycleListener {

    @Autowired
    private FreemarkerService freemarkerService;

    @Override
    public void onMessage(Object o) {
        System.out.println(o);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt message = list.get(0);
                int reconsumeTimes = message.getReconsumeTimes();
                /*
                 * 重试的次数
                 * */
                try {
                    //System.out.println(message.getTopic());
                    String goodsId = new String(message.getBody(),"utf-8");
                    //json字符传递的然后
                    List<Long> longs = JSONArray.parseArray(goodsId, Long.class);
                   // System.out.println("消息" +longs);
                    //System.out.println(longs.get(0));
                    //System.out.println(longs);
                    for (int i = 0; i < longs.size(); i++) {
                        Long aLong = longs.get(i);
                        freemarkerService.createPage(aLong);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (reconsumeTimes > 2) {
                        System.out.println("重试次数超过两次，就不再消费，将错误信息保存到数据库的死信队列");
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}
